﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.BO;
using PPAP.Model;
using System.Data;

namespace PPAP.Web.Part
{
    public partial class SamplingCapbility : PageBase
    {
        PPARBO pbo = new PPARBO();
        LogBO lbo = new LogBO();
        SignBO sbo = new SignBO();
        MailTemplateBO mbo = new MailTemplateBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["RID"] != null)
                {
                    PPAR pp = pbo.GetModel(int.Parse(Request.QueryString["RID"].ToString()));
                    if (pp != null)
                    {
                        rbtYesa.Checked = pp.ISCAPABILITYDOCUMENT == 1 ? true : false;
                        rbtNoa.Checked = pp.ISCAPABILITYDOCUMENT == 0 ? true : false;
                        rbtYesb.Checked = pp.ISCAPABILITYPART == 1 ? true : false;
                        rbtNob.Checked = pp.ISCAPABILITYPART == 0 ? true : false;
                        TextBox1.Text = pp.CAPABILITYFEEDBACK;
                        if (pp.STATUS == 2 && (Request.QueryString["his"] != null && Request.QueryString["his"].ToString() == "0")) //状态等于2并且不是从history页面跳转过来
                        {
                            btnSubmit.Visible = true;
                           
                        }
                        else
                        {
                            btnSubmit.Visible = false;
                            rbtNoa.Enabled = false;
                            rbtNob.Enabled = false;
                            rbtYesa.Enabled = false;
                            rbtYesb.Enabled = false;
                            TextBox1.Enabled = false;
                        }
                        if (pp.ISWITHOUTSAMPLE == 1)
                            ta.Visible = false;
                        PPAP.Model.Sign s = sbo.GetModelByPPARID(int.Parse(pp.ID.ToString()));
                        if (s != null)
                        {
                            txtDATE.Text = DateTime.Parse(s.RECEIVEDATE.ToString()).ToString("yyyy-MM-dd");
                            txtRemark.InnerHtml = s.SIGNREMARK.Replace("\r\n", "<br>").Replace("\n", "<br>");
                            txtQuantity.Text = s.RECEIVEQUANTITY.ToString();
                            txtReceiver.Text = s.SIGNPROCESSOR;
                            //txtReceiverdate.Text = DateTime.Parse(s.RECEIVEDATE.ToString()).ToString("yyyy-MM-dd");
                        }
                        else
                            tr2.Visible = true;
                        if (pp.STATUS <= 2 && pp.CAPABILITYFEEDBACK=="")
                        {
                            rbtNoa.Checked = false;
                            rbtYesa.Checked = false;
                            rbtNob.Checked = false;
                            rbtYesb.Checked = false;
                        }
                        rbtYesa_CheckedChanged(null, null);
                    }
                }
            }
        }

        protected void rbtYesa_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtYesa.Checked && rbtYesb.Checked)
                lblStatus.Text = "PPAR ready for sampling";
            else if (rbtNoa.Checked || rbtNob.Checked)
                lblStatus.Text = "PPAR not ready for sampling";
            else
                lblStatus.Text = "";
            TextBox1_TextChanged(null, null);
        }

        /// <summary>
        /// Submit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (rbtNoa.Checked == false && rbtNob.Checked == false && rbtYesa.Checked == false && rbtYesb.Checked == false)
            {
                AlertMessage("Please select documents&part");
                return;
            }
            if (Request.QueryString["RID"] != null)
            {
                TextBox1.Text = CheckWord(TextBox1.Text);
                PPAR pp = pbo.GetModel(int.Parse(Request.QueryString["RID"].ToString()));
                if (pp != null)
                {
                    
                    if (rbtYesa.Checked && rbtYesb.Checked)
                    {
                        pp.STATUS = 3;

                        //如果没有物流信息，将提醒
                        if (pp.ISWITHOUTSAMPLE == 0)  //有物流但没收到
                        {
                            PPAP.Model.Sign s = sbo.GetModelByPPARID(int.Parse(pp.ID.ToString()));
                            if (s == null)
                            {
                                AlertMessage("Please noted no logistics information");
                            }
                        }
                    
                    }
                    else
                        pp.STATUS = 4;

                    //发邮件
                    MailTemplate mail = null;
                    if (pp.STATUS == 3)
                        mail = mbo.GetModel(3);
                    else
                        mail = mbo.GetModel(4);
                    DataSet dsmail = mbo.GetEDM3(pp.ID.ToString());
                    if (mail != null && dsmail.Tables[0].Rows.Count > 0)
                    {
                        if (dsmail.Tables[0].Rows[0]["submittedby"].ToString() != "")
                        {
                            string title = mail.TITLE.Replace("{Part No.}", dsmail.Tables[0].Rows[0]["bdntpartno"].ToString());
                            title = title.Replace("{Part name}", dsmail.Tables[0].Rows[0]["bdntpartname"].ToString());
                            title = title.Replace("{Color}", dsmail.Tables[0].Rows[0]["color"].ToString());
                            try
                            {
                                base.SendEmailToUser(dsmail.Tables[0].Rows[0]["submittedby"].ToString(), title, mail.CONTENT, dsmail.Tables[0].Rows[0]["username"].ToString() == "" ? null : dsmail.Tables[0].Rows[0]["username"].ToString());
                                lbo.WriteLog(CurrentUser.Id, "Send Email:" + dsmail.Tables[0].Rows[0]["submittedby"].ToString(), Request.QueryString["rid"].ToString());

                            }
                            catch (Exception ex)
                            {
                                AlertMessage(ex.Message.ToString());
                                lbo.WriteLog(CurrentUser.Id, "Send Email:" + ex.Message.ToString(), Request.QueryString["rid"].ToString());
                            }
                        }
                        else
                        {
                            foreach (DataRow dr in dsmail.Tables[0].Rows)
                            {
                                string title = mail.TITLE.Replace("{Part No.}", dr["bdntpartno"].ToString());
                                title = title.Replace("{Part name}", dr["bdntpartname"].ToString());
                                try
                                {
                                    base.SendEmailToUser(dr["username"].ToString(), title, mail.CONTENT, null);
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + dr["username"].ToString(), Request.QueryString["rid"].ToString());

                                }
                                catch (Exception ex)
                                {
                                    AlertMessage(ex.Message.ToString());
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + ex.Message.ToString(), Request.QueryString["rid"].ToString());
                                }
                            }
                        }
                    }
                    //发邮件

                    pp.ISCAPABILITYDOCUMENT = rbtYesa.Checked ? 1 : 0;
                    pp.ISCAPABILITYPART = rbtYesb.Checked ? 1 : 0;
                    pp.CAPABILITYFEEDBACK = TextBox1.Text;
                    int num = pbo.UpdateForQe(pp);
                    if (num > 0)
                    {
                        btnSubmit.Visible = false;
                        rbtNoa.Enabled = false;
                        rbtNob.Enabled = false;
                        rbtYesa.Enabled = false;
                        rbtYesb.Enabled = false;
                        lbo.WriteLog(CurrentUser.Id, "Submit Sampling Capbility:" + lblStatus.Text, pp.ID.ToString());
                        // Response.Write("<script language=javascript>top.frames['menu'].location.reload();</script>");
                        if (pp.STATUS == 3)
                            Response.Write("<script>top.frames['mainFrame'].location=top.frames['mainFrame'].location;</script>");
                        else
                        {
                            //sbo.DeleteByPPARID(int.Parse(pp.ID.ToString()));
                            Response.Write("<script language=javascript>top.frames['menu'].location.reload();</script>");
                            Response.Write("<script>top.frames['mainFrame'].location='CreatPPAR.aspx'</script>");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 自动保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (Request.QueryString["RID"] != null)
                {
                    if ((rbtNoa.Checked != false || rbtYesa.Checked != false) && (rbtNob.Checked != false || rbtYesb.Checked != false))
                    {
                        PPAR pp = pbo.GetModel(int.Parse(Request.QueryString["RID"].ToString()));
                        if (pp != null)
                        {
                            pp.ISCAPABILITYDOCUMENT = rbtYesa.Checked ? 1 : 0;
                            pp.ISCAPABILITYPART = rbtYesb.Checked ? 1 : 0;
                            pp.CAPABILITYFEEDBACK = TextBox1.Text==""?" ":TextBox1.Text;
                            pbo.UpdateForQe(pp);
                        }
                    }
                }
            }
        }
    }
}